package com.lxh.empwork.web.servlet;

import com.lxh.empwork.common.Const;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            //获取方法
            String method = req.getParameter("method");
            System.out.println(method);
            //反射
            Class aClass = this.getClass();
            //查找方法
            Method method1 = aClass.getMethod(method, HttpServletRequest.class,HttpServletResponse.class);
            System.out.println(method1);
            //调用
            String result = (String) method1.invoke(this, req,resp);
            //判断做什么操作
            if(result!=null){
                if(result.contains(Const.FORWARD)){
                    req.getRequestDispatcher(result.replace(Const.FORWARD, "" )).forward(req, resp);
                }else if(result.contains(Const.REDIRECT)){
                    resp.sendRedirect(result.replace(Const.REDIRECT, ""));
                }else {
                    resp.getWriter().println(result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendRedirect(req.getContextPath()+"/error.jsp");
        }
    }
}
